/*
 * @Author       : 邱狮杰
 * @Date         : 2021-05-19 16:45:16
 * @LastEditTime : 2021-05-20 10:26:36
 * @FilePath     : /wedding-dress-selection/src/reducer/like.tsx
 * @Description  : like reducer
 */
import { useReducer, createContext, Dispatch } from 'react'
export const CreateLike = createContext({})
// 编辑状态修改
export const EDITCHANGE = 'editChange'
// 覆盖
export const RESET = 'reset'
// 编辑item状态
export const EDITCHECK = 'editCheck'
// 编辑某个Item
export const ITEMEDIT = 'itemEdit'
// edit delete
export const DELETE = 'delete'
interface editItem {
  index: number
  state: boolean
}
interface StateConfig {
  id: number
  edit: boolean
  check: boolean
  designSrc: string
}
interface Action {
  type: typeof EDITCHANGE | typeof RESET | typeof EDITCHECK | typeof DELETE | typeof ITEMEDIT
  data?: StateConfig[] | boolean | editItem
}
export interface useLikeContextType {
  likeState: StateConfig[]
  likeDispatch: Dispatch<Action>
}
function reducerLike(state: StateConfig[], action: Action) {
  switch (action.type) {
    case EDITCHANGE:
      // action.data is boolean
      return [...state.map(item => Object.assign(item, { edit: action.data }))]
    case EDITCHECK:
      // action.data is boolean
      return [...state.map(item => Object.assign(item, { check: action.data }))]
    case DELETE:
      // deletes
      return [...state.filter(item => item.check === false)]
    case RESET:
      // action.data is StateConfig[]
      return action.data as StateConfig[]
    case ITEMEDIT:
      const cur = state[(action.data as editItem).index]
      cur.check = (action.data as editItem).state
      state[(action.data as editItem).index] = cur
      return [...state]
    default:
      return state
  }
}

export const LikeContext = (props: any) => {
  const [likeState, likeDispatch] = useReducer(reducerLike, [])
  return <CreateLike.Provider value={{ likeState, likeDispatch }}>{props.children}</CreateLike.Provider>
}
